package com.mcz.yun4book.config;

import com.mcz.yun4book.service.impl.MyUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
public class SecurityConfiguartion extends WebSecurityConfigurerAdapter {
    @Autowired
    private MyUserDetailsService myUserDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/user/login","/css/**","/js/**","/images/**","/lib/**").
                permitAll().antMatchers("/book/list").hasAnyRole("ADMIN","USER")
                .antMatchers("/book/add","/book/edit","/book/del").hasRole("ADMIN")
                .anyRequest().authenticated();

        http.formLogin().loginPage("/user/login").defaultSuccessUrl("/");
        http.headers().frameOptions().sameOrigin();
        http.csrf().disable();

        //用403界面
        http.exceptionHandling().accessDeniedPage("/user/403");
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserDetailsService).passwordEncoder(passwordEncoder());
    }
    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}
